package com.topscomm.mpm.xxlJob;

import com.topscomm.basic.BasicEntity;
import com.topscomm.mpm.pojo.MpmProjectMilepostEntity;
import com.topscomm.mpm.pojo.MpmProjectTaskEntity;
import com.topscomm.mpm.service.IMpmProjectMilepostService;
import com.topscomm.mpm.service.impl.MpmProjectMilepostService;
import com.topscomm.mpm.service.impl.MpmProjectTaskService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author wudaliang
 * @date 2021/3/19
 * @description: 检查进行中的项目的里程碑及任务的状态，如果里程碑及任务下挂载的全部任务完成，则把里程碑及任务状态置为达成，
 * 注意，如果里程碑及任务下边还没有挂载任务，则不对它进行处理。
 * @modify:
 */
@JobHandler(value = "projectMilePostCheck")
@Component
public class ProjectMilePostCheckJob extends IJobHandler {

    @Autowired
    private IMpmProjectMilepostService mpmProjectMilepostService;
    @Autowired
    private MpmProjectTaskService mpmProjectTaskService;
    @Override
    public ReturnT<String> execute(String param) throws Exception {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" EXISTS(SELECT * from MPMPROJECTTASK WHERE MPMPROJECTTASK.MILEPOSTCODE=MPMPROJECTMILEPOST.OPERATECODE)  AND ENABLED=1 AND MILEPOSTSTATE=0");
        List<MpmProjectMilepostEntity> mpmProjectMilepostEntityList = mpmProjectMilepostService
            .queryByWhere(sql.toString());
        // 查询出的里程碑及任务下挂载的任务全都已完成，则把里程碑及任务置为达成
        String milepostcodes = mpmProjectMilepostEntityList.stream()
                .map(s->"'"+ConvertUtil.convertToString(s.getOperatecode())+"'")
                .collect(Collectors.joining(","));
        sql.clear();
        Map<String,MpmProjectMilepostEntity> updateMap = new HashMap<>();
        List<String> updateCodes = new ArrayList<>();
        sql.appendSingle(" MILEPOSTCODE in ({0}) AND TASKSTATE in (0,1) and enabled=1 ",milepostcodes);
        List<MpmProjectTaskEntity> taskEntities = mpmProjectTaskService.queryByWhere(sql.toString());
        Map<String ,List<MpmProjectTaskEntity>> taskGroupMaps = taskEntities.stream().collect(Collectors.groupingBy(t->ConvertUtil.convertToString(t.getMilepostcode())));
        // 需要更新的里程碑及任务
        for(MpmProjectMilepostEntity milepostEntity: mpmProjectMilepostEntityList) {
            String milepostCode = ConvertUtil.convertToString(milepostEntity.getOperatecode());
            if(!taskGroupMaps.containsKey(milepostCode)) {
                updateMap.put(milepostCode,milepostEntity);
                updateCodes.add(milepostCode);
            }
        }
        List<BasicEntity> updateEntities = new ArrayList<>();
        String updateCodesString = updateCodes.stream().collect(Collectors.joining("','","'","'"));
        sql.clear();
        sql.appendSingle("MILEPOSTCODE in ({0}) order by  ACTUALENDDATE DESC ",updateCodesString);
        List<MpmProjectTaskEntity> taskEntities2 = mpmProjectTaskService.queryByWhere(sql.toString());
        Map<String ,List<MpmProjectTaskEntity>> taskGroupMaps2 = taskEntities2.stream().collect(Collectors.groupingBy(t->ConvertUtil.convertToString(t.getMilepostcode())));
        for(String key:taskGroupMaps2.keySet()) {
            if(updateMap.containsKey(key)) {
                MpmProjectMilepostEntity temp = updateMap.get(key);
                MpmProjectTaskEntity first = taskGroupMaps2.get(key).get(0);
                temp.setMilepoststate(1);
                temp.setActualfinishtime(first.getActualenddate());
                updateEntities.add(temp);
            }
        }
        if (updateEntities.size()>0) {
            mpmProjectMilepostService.updateBatch(updateEntities);
        }

        List<BasicEntity> updateList = new ArrayList<>();
        for (MpmProjectMilepostEntity e:mpmProjectMilepostEntityList) {
            // 里程碑及任务的operatecode对应任务的milepostcode
            // 里程碑及任务下不存在开始和进行中的任务，则把里程碑及任务置为达成
            sql.clear();
            sql.appendSingle(" MILEPOSTCODE='{0}' AND TASKSTATE in (0,1) and enabled=1 ",e.getOperatecode());
            List<MpmProjectTaskEntity> mpmProjectTaskEntities = mpmProjectTaskService
                .queryByWhere(sql.toString());
            //里程碑及任务的全部任务已完成
            if(mpmProjectTaskEntities.size()==0){
                //把里程碑及任务置为达成
                sql.clear();
                sql.appendSingle(" MILEPOSTCODE='{0}' order by  ACTUALENDDATE DESC ",e.getOperatecode());
                List<MpmProjectTaskEntity> mpmProjectTaskEntities1 = mpmProjectTaskService
                    .queryByWhere(sql.toString());
                e.setMilepoststate(1);
                e.setActualfinishtime(mpmProjectTaskEntities1.get(0).getActualenddate());
                updateList.add(e);
            }
        }
        //  mpmProjectMilepostService.updateBatch(updateList);
        return ReturnT.SUCCESS;
    }
}
